package blacklistoperationlogic

import (
	"context"
	"strings"

	"dfx_cmdb/cmdb-blacklist-rpc/internal/svc"
	cmdb_blacklist_rpc "dfx_cmdb/cmdb-blacklist-rpc/types/cmdb-blacklist-rpc"
	cmdbblacklist "dfx_cmdb/models/cmdb-blacklist"

	"github.com/zeromicro/go-zero/core/logc"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetAllBlacklistLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetAllBlacklistLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetAllBlacklistLogic {
	return &GetAllBlacklistLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 获取所有黑名单列表
func (l *GetAllBlacklistLogic) GetAllBlacklist(in *cmdb_blacklist_rpc.GetAllBlacklistRequest) (*cmdb_blacklist_rpc.BlacklistResponse, error) {
	// todo: add your logic here and delete this line
	logc.Debugf(l.ctx, "开始获取黑名单列表: %s", in.Type)
	redisGetBlacklistMap, err := RedisReader(l.ctx, l.svcCtx, "blacklist:"+in.Type)
	if err != nil {
		return nil, err
	}
	respBlacklistMap := make(map[string]*cmdb_blacklist_rpc.StringList)
	for key, value := range redisGetBlacklistMap {
		if value == nil {
			value = []string{}
		}
		respBlacklistMap[key] = &cmdb_blacklist_rpc.StringList{Values: value}
	}

	for key, value := range respBlacklistMap {
		strAry := strings.Split(key, "_")
		logc.Debugf(l.ctx, "---------------------------key: %s", key)
		if len(strAry) < 2 {
			continue
		}
		respBlacklistMap[key].Port = strAry[len(strAry)-1]
		respBlacklistMap[key].Count = int32(len(value.Values))
	}
	ignoreVal := &cmdbblacklist.BlacklistIgnoreRule{}
	err = l.svcCtx.PDB.WithContext(l.ctx).
		Where("ignore_type = ? AND enable = ?", "set", true).
		First(&ignoreVal).Error

	if err == nil && ignoreVal.IgnoreVal != "" {
		ignoreSet := strings.Split(ignoreVal.IgnoreVal, ",")
		logc.Debugf(l.ctx, "已应用Set忽略规则，忽略的Set有: %v", ignoreSet)
		for _, set := range ignoreSet {
			trimmedSet := strings.TrimSpace(set)
			if trimmedSet != "" {
				delete(respBlacklistMap, trimmedSet)
				logc.Debugf(l.ctx, "已删除忽略的Set: %s", trimmedSet)
			}
		}
	} else if err != nil {
		logc.Debugf(l.ctx, "未找到启用的Set忽略规则或查询失败: %v", err)
	}

	return &cmdb_blacklist_rpc.BlacklistResponse{
		Blacklist: respBlacklistMap,
	}, nil
}
